<template>
  <view>
    <view class="page-top-place"></view>
    <view class="page-content">
      <view class="content-card-title am-flex-row-center">商品信息</view>
      <template>
        <view v-if="pageQuery.pType === 'cart'">
          <view
            class="company-section"
            v-for="item in carArrData"
            :key="item.id"
          >
            <view class="goods-item">
              <view class="goods-cover">
                <image
                  :src="$imageCutting(item.banner.split(',')[0], 120, 120)"
                  mode="aspectFill"
                  class="goods-cover-img am-wh-100 am-block"
                ></image>
              </view>
              <view class="goods-con">
                <view class="goods-name-wrap">
                  <text class="goods-name am-line-clamp-two am-text-break">{{
                    item.name
                  }}</text>
                  <text class="specStyle">{{ item.spec }}</text>
                </view>
                <view class="am-flex-rc-between goods-price-wrap">
                  <view class="goods-price">
                    <text class="goods-price-unit">￥</text>
                    <text>{{ item.finalProxyPrice }}元</text>
                  </view>
                  <view class="goods-price-num">x{{ item.num }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view v-else-if="pageQuery.pType === 'goods'">
          <view class="goods-item">
            <view class="goods-cover"
              ><image
                :src="cardData.banner"
                mode="aspectFill"
                class="goods-cover-img am-wh-100 am-block"
              ></image
            ></view>
            <view class="goods-con">
              <view class="goods-name-wrap">
                <text class="goods-name am-line-clamp-two am-text-break">{{
                  cardData.name
                }}</text>
                <text class="specStyle">{{ cardData.spec }}</text>
              </view>
              <view class="am-flex-rc-between goods-price-wrap">
                <view class="goods-price">
                  <text class="goods-price-unit">￥</text>
                  <text>{{ cardData.price }}元</text>
                </view>
                <view class="goods-price-num">
                  <u-number-box
                    v-model="cardData.num"
                    :min="1"
                    :max="cardData.stock"
                    :long-press="false"
                    :input-height="54"
                    :input-width="86"
                  ></u-number-box>
                </view>
              </view>
            </view>
          </view>
        </view>
      </template>
      <u-cell-group :border="false"
        ><u-cell-item
          :hover-class="none"
          title="运费"
          :value="freightShow"
          :arrow="false"
        ></u-cell-item
      ></u-cell-group>
      <view class="content-card-title am-flex-row-center">
        收货信息
        <text class="tip">（您可以选择客户名称或直接输入客户信息）</text>
      </view>
      <u-cell-group :border="false">
        <u-cell-item
          title="我的地址"
          value="请选择"
          @click="chooseCustomer"
        ></u-cell-item>
        <!-- <u-cell-item
          :use-label-slot="true"
          :arrow="false"
          :title-width="654"
          hover-class="none"
        >
          <view class="" slot="label">
            <view class="receiving-address">
              <template v-if="showTextarea">
                <u-input
                  type="textarea"
                  v-model="receivingAddress"
                  :height="250"
                  :maxlength="100"
                  placeholder="粘贴或输入文本，点击“识别”自动识别联系、收件人、联系电话、收货地"
                  :custom-style="receivingAddressSty"
                ></u-input>
                <view
                  class="receiving-address__btn"
                  hover-class="receiving-address__btn-hover"
                  @click.stop="addressTextGet"
                  >识别</view
                >
              </template>
              <template v-else>
                <view style="min-height: 120px">{{ receivingAddress }}</view>
              </template>
            </view>
          </view>
        </u-cell-item> -->
        <u-cell-item title="收货人" :arrow="false">
          <view class="f-cell-item">
            <view class="f-cell-item-input">
              <u-input
                v-if="showTextarea"
                v-model="consignee"
                input-align="right"
                placeholder="请输入"
                :maxlength="20"
              ></u-input>
              <view v-else>{{ consignee }}</view>
            </view>
          </view>
        </u-cell-item>
        <u-cell-item title="收货电话" :arrow="false">
          <view class="f-cell-item">
            <view class="f-cell-item-input">
              <u-input
                v-if="showTextarea"
                v-model="receivingPhone"
                input-align="right"
                placeholder="请输入"
                :maxlength="11"
              ></u-input>
              <view v-else>{{ receivingPhone }}</view>
            </view>
          </view>
        </u-cell-item>
        <u-cell-item title="省-市-区" :arrow="false">
          <view class="f-cell-item">
            <view class="f-cell-item-input">
              <co-address-picker
                @change="addressPickerChange"
                :value="addressValue"
              >
                <view v-show="!regionStr">
                  请选择
                  <u-icon name="arrow-right"></u-icon>
                </view>
                <view>{{ regionStr }}</view>
              </co-address-picker>
              <picker mode="region" @change="regionChange"></picker>
            </view>
          </view>
        </u-cell-item>
        <view @click="toPosition"
          ><u-cell-item title="详细地址" :arrow="false">
            <view class="f-cell-item">
              <view class="f-cell-item-input">
                <input
                  v-if="showTextarea"
                  v-model="detailedAddress"
                  input-align="right"
                  placeholder="请输入详细地址"
                  :maxlength="100"
                />
                <view v-else>{{ detailedAddress }}</view>
              </view>
            </view>
          </u-cell-item></view
        >
      </u-cell-group>
    </view>

    <payment-method
      ref="paymentRef"
      @payFail="payFailCb"
      @paySuccess="paySuccessCb"
      :scene="payScene"
    ></payment-method>
    <view class="err-tip" v-if="isPinkage"
      >当前收货地址卖家不支持配送，请修改收货地</view
    >
    <view class="footer-bar am-flex-rc-between">
      <view class="footer-bar-total">
        合计：
        <text class="footer-bar__total-price">{{ totalPrice }}</text>
        <text>（含运费：{{ freightShow }}）</text>
      </view>
      <view>
        <button
          class="u-reset-button submit-button"
          :class="{ 'disable-btn': !getDetailsSuccess }"
          hover-class="submit-button-hover"
          @click="submitOrder"
          :loading="submitOrderLoading"
        >
          提交订单
        </button>
      </view>
    </view>
    <view class="footer-bar-place"></view>
  </view>
</template>

<script>
import { apiAddressGet } from '@/api/common.js'
import { apiCartOrder, apiGoodsToOrder } from '@/api/order'
import {
  CHOOSE_RECEIVING_ADDRESS,
  UPDATE_SHOPPING_CART
} from '@/types/globalEventName'
import { levelToPriceField } from '@/types/goods.js'
import Big from 'big.js'

export default {
  data() {
    return {
      receivingAddress: '', // 收货地址
      receivingAddressSty: {
        fontSize: '30rpx',
        color: '#333',
        lineHeight: '42rpx'
      },
      pinkageParams: {
        consigneeProvinceId: '',
        pidList: []
      }, // 判断包邮
      consignee: '', // 收货人
      receivingPhone: '', // 收货电话
      regionStr: '',
      detailedAddress: '', // 详细地址
      remark: '', // 备注
      pageQuery: {},
      addressCode: [],
      addressValue: [],
      submitOrderLoading: false,
      cartOrderData: [],
      goodsNum: 1,
      orderDetails: {},
      getDetailsSuccess: false,
      createdOrderData: [], // 生成订单后的数据
      payScene: 'cart', // 支付场景
      showTextarea: true,
      cardData: {},
      carArrData: [],
      freight: null,
      isPinkage: false,
      postalMarketList: [
        '622901',
        '622921',
        '622922',
        '622923',
        '622924',
        '622925',
        '622926',
        '622927'
      ]
    }
  },
  /**
   * @param {Object} option
   * @param {String} option.pType [goods|cart] - 下单来源购物车、商品.默认goods
   * @param {String} option.ids
   * */
  onLoad(option) {
    if (!option.pType) {
      option.pType = 'goods'
    }
    this.pageQuery = option
    console.log(this.pageQuery, '-=-=-=-=')

    if (option.pType === 'cart') {
      this.payScene = 'cart'
      this.getCartOrderData()
    } else {
      this.payScene = 'goods'
      this.getOrderData()
    }
    uni.$on(CHOOSE_RECEIVING_ADDRESS, this.chooseReceiving)
    let obj = uni.getStorageSync('site')
    this.consignee = obj.consignee
    this.receivingPhone = obj.receivingPhone
    this.addressCode = obj.addressCode
    this.addressValue = obj.addressValue
    this.detailedAddress = obj.detailedAddress
    this.latitude = obj.latitude
    this.longitude = obj.longitude
    this.regionStr = obj.regionStr
    // this.pinkageParams.consigneeProvinceId = obj.addressCode[0]
    if (option.pType === 'cart') {
      this.checkPinkage()
    }
    console.log(obj)
  },
  onUnload() {
    uni.$off(CHOOSE_RECEIVING_ADDRESS, this.chooseReceiving)
  },
  watch: {
    'cardData.num': {
      handler(v) {
        this.pinkageParams.pidList[0].num = v
        this.pinkageParams.pidList[0].price = this.cardData.price * v
        this.checkPinkage()
      },
      immediate: false
    }
  },
  computed: {
    // shopNum(){
    // 	return this.cardData.num
    // },
    totalPrice() {
      if (!this.getDetailsSuccess) return 0
      let total = new Big(0)
      if (this.pageQuery.pType === 'goods') {
        total = total.plus(
          new Big(this.cardData.num).times(this.cardData.price)
        )
      } else if (this.pageQuery.pType == 'cart') {
        this.carArrData.forEach((z1) => {
          total = total.plus(new Big(z1.num).times(z1.finalProxyPrice))
        })
      }
      return Number(total) + this.freight
    },
    curSupplierLevel() {
      return this.$store.getters.curSupplierLevel
    },
    freightShow() {
      return '￥' + (this.freight ? this.freight.toFixed(2) : '0.00')
    }
  },
  methods: {
    toPosition(e) {
      // console.log(e, 'bindtapbindtapbindtapbindtap')
      // var that = this
      // uni.chooseLocation({
      //   success: function (lb) {},
      //   complete: function (lb) {
      //     that.detailedAddress = lb.name
      //     that.latitude = lb.latitude
      //     that.longitude = lb.longitude
      //     console.log(that.detailedAddress, '_++__+_++_++_+')
      //   },
      //   cancel: function (lb) {},
      //   fail: function (lb) {
      //     console.log(lb)
      //   }
      // })
    },
    // 校验包邮
    checkPinkage(v) {
      if (this.cardData.name == '公益活动返还金' || this.cardData.id == 15) {
        this.freight = 0
        return
      }
      let areaCode = v || this.addressCode[2]
      if (this.postalMarketList.includes(areaCode)) {
        if (areaCode == '622901') {
          this.freight = 8
        } else {
          this.freight = 12
        }
      } else {
        this.getDetailsSuccess = false
        this.isPinkage = true
      }
      // let res = await checkPinkage(this.pinkageParams)
      // console.log(res, '-=-=-=-=-')
      // if (
      //   res.data.code === '200' &&
      //   res.data.data.judgeMailNotPackageSearchDTOList
      // ) {
      //   let stateArr = res.data.data.judgeMailNotPackageSearchDTOList.map(
      //     (item) => item.state
      //   )
      //   if (stateArr.includes(2)) {
      //     this.getDetailsSuccess = false
      //     this.isPinkage = true
      //   } else {
      //     this.getDetailsSuccess = true
      //     this.freight = res.data.data.freight
      //     this.isPinkage = false
      //   }
      // }
    },
    getOrderData() {
      this.getDetailsSuccess = true
      this.cardData = JSON.parse(this.pageQuery.val)
      console.log(this.cardData, '直接购买进入')
      let { sku, pid, num, price } = this.cardData
      this.pinkageParams.pidList.push({
        sku,
        pid,
        num,
        price: num * price
      })
      // console.log(this.cardData);
    },
    regionChange(e) {
      this.regionStr = e.detail.value.join('')
    },
    addressPickerChange(e) {
      this.checkPinkage(e.code[2])
      this.pinkageParams.consigneeProvinceId = e.code[0] // 设置包邮参数
      this.regionStr = e.name.join('-')
      this.addressCode = e.code
    },
    // 选择了收货地址
    chooseReceiving(p_data) {
      console.log('用户选择地址后回调', p_data)
      this.pinkageParams.consigneeProvinceId = p_data.consigneeProvinceId // 设置包邮参数
      this.checkPinkage(p_data.consigneeCountyId)
      this.consignee = p_data.consigneeName
      this.receivingPhone = p_data.consigneePhone
      this.detailedAddress = p_data.consigneeAddress
      this.latitude = p_data.latitude
      this.longitude = p_data.longitude
      this.addressValue = [
        p_data.consigneeProvinceId,
        p_data.consigneeCityId,
        p_data.consigneeCountyId
      ]
      this.regionStr = `${p_data.consigneeProvince}-${p_data.consigneeCity}-${p_data.consigneeCounty}`
      this.addressCode = [
        p_data.consigneeProvinceId,
        p_data.consigneeCityId,
        p_data.consigneeCountyId
      ]
    },
    // 点击去选择客户地址
    chooseCustomer() {
      this.$u.route('/pages/customer/customer-list', { pType: 'choose' })
    },
    // 查询用购物车进入的信息
    getCartOrderData() {
      this.getDetailsSuccess = true
      this.carArrData = JSON.parse(this.pageQuery.val)
      console.log(this.carArrData, '查询用购物车进入的信息')
      this.carArrData.forEach((item) => {
        this.pinkageParams.pidList.push({
          sku: item.sku,
          pid: item.pid,
          num: item.num,
          price: item.num * item.finalProxyPrice
        })
      })
      // uni.showLoading({
      // 	mask: true
      // });
      // let ids = this.pageQuery.ids;
      // apiCheckCartData(ids.split(','))
      // 	.then(res => {
      // 		let { state, msg, data } = res.data;
      // 		if (state === 'OK') {
      // 			console.log(data);
      // 			this.cartOrderData = data;
      // 			this.getDetailsSuccess = true;
      // 			uni.hideLoading();
      // 		} else {
      // 			uni.hideLoading();
      // 			this.$am_toast.warning(msg);
      // 		}
      // 	})
      // 	.catch(() => {
      // 		uni.hideLoading();
      // 		this.$am_toast.warning('查询失败，请重新尝试！');
      // 	});
    },
    // 提交订单
    submitOrder() {
      if (this.submitOrderLoading) return
      if (!this.consignee) {
        this.$am_toast('请输入收货人名称')
        return
      } else if (this.receivingPhone.length < 11) {
        this.$am_toast('收货电话格式不正确')
        return
      } else if (this.addressCode.length !== 3) {
        this.$am_toast('请选择省市区')
        return
      } else if (!this.detailedAddress) {
        this.$am_toast('请输入详细地址')
        return
      }
      uni.setStorageSync('site', {
        consignee: this.consignee,
        receivingPhone: this.receivingPhone,
        addressCode: this.addressCode,
        addressValue: this.addressValue,
        detailedAddress: this.detailedAddress,
        latitude: this.latitude,
        longitude: this.longitude,
        regionStr: this.regionStr
      })
      this.submitOrderLoading = true
      if (this.pageQuery.pType === 'cart') {
        this.cartToOrder()
      } else {
        this.goodsToOrder()
      }
    },

    cartToOrder() {
      apiCartOrder({
        cartIds: this.pageQuery.ids.split(','),
        consigneeAddress: this.detailedAddress,
        latitude: this.latitude,
        longitude: this.longitude,
        consigneeCityId: this.addressCode[1],
        consigneeCountyId: this.addressCode[2],
        consigneeName: this.consignee,
        consigneePhone: this.receivingPhone,
        consigneeProvinceId: this.addressCode[0],
        freight: this.freight
      })
        .then((res) => {
          let { state, msg, data } = res.data
          if (state === 'OK') {
            uni.$emit(UPDATE_SHOPPING_CART)
            this.$store.dispatch('getCartNum')
            this.$store.dispatch('getNoticeData')
            // uni.$emit(UPDATE_ORDER_LIST);
            this.createdOrderData = data
            // this.showTextarea = false
            // this.$refs.paymentRef.pay_out(data.map(p1 => p1.oid));

            this.createdOrderData = [data]
            this.$refs.paymentRef.pay_out([data.oid])
          } else {
            this.$am_toast.warning(msg)
          }
          this.submitOrderLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.$am_toast.warning('操作失败，请重新尝试！')
          this.submitOrderLoading = false
        })
    },
    // 商品下单
    goodsToOrder() {
      apiGoodsToOrder({
        id: this.pageQuery.ids,
        consigneeAddress: this.detailedAddress,
        latitude: this.latitude,
        longitude: this.longitude,
        consigneeCityId: this.addressCode[1],
        consigneeCountyId: this.addressCode[2],
        consigneeName: this.consignee,
        consigneePhone: this.receivingPhone,
        consigneeProvinceId: this.addressCode[0],
        consigneeRemarks: this.remark,
        freight: this.freight,
        productSkuInfo: {
          num: this.cardData.num,
          pid: this.cardData.pid,
          sku: this.cardData.sku
        }
      })
        .then((res) => {
          console.log(res, '*********')
          let { state, msg, data } = res.data
          if (state === 'OK') {
            uni.$emit(UPDATE_SHOPPING_CART)
            this.$store.dispatch('getCartNum')
            this.$store.dispatch('getNoticeData')
            // uni.$emit(UPDATE_ORDER_LIST);
            // this.$refs.payPanelRef.pay_out([data]);
            // TODO 测试
            this.createdOrderData = [data]
            this.showTextarea = false
            this.$refs.paymentRef.pay_out([data.oid])
          } else {
            this.$am_toast.warning(msg)
          }
          this.submitOrderLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.$am_toast.warning('操作失败，请重新尝试！')
          this.submitOrderLoading = false
        })
    },
    // 支付失败
    payFailCb(p_data) {
      console.log('取消支付')
      console.log(p_data)
      if (p_data.scene === 'goods') {
        uni.redirectTo({
          url: `/pages/order/order-details?id=${this.createdOrderData[0].id}`
        })
      } else {
        uni.redirectTo({
          url: '/pages/place-order/pay-result?isFail=1'
        })
      }
    },
    // 支付成功
    paySuccessCb() {
      uni.redirectTo({
        url: '/pages/place-order/pay-result'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
$section-plr: 19rpx;
.page-top-place {
  height: 16rpx;
}
.page-content {
  margin: 0 16rpx 16rpx;
  padding: 0 24rpx;
  background: #ffffff;
  border-radius: 16rpx;
}
.content-card-title {
  height: 80rpx;
  padding: 0 $section-plr;
  font-size: 36rpx;
  font-weight: 500;
  .tip {
    font-size: 24rpx;
    color: #999;
  }
}
.company-section {
  margin-left: $section-plr;
  margin-right: $section-plr;
  & + .company-section {
    margin-top: 15rpx;
    border-top: 1px solid #e8e8e8;
  }
}
.company-section-title {
  padding-top: 18rpx;
  font-size: 24rpx;
  color: #000000;
}
.products-wrap {
  padding: 30rpx $section-plr 0;
}
.goods-item {
  display: flex;
  align-items: stretch;
  padding: 15rpx 0;
  & + .goods-item {
    // margin-top: 30rpx;
  }
}
.goods-cover {
  overflow: hidden;
  width: 150rpx;
  height: 150rpx;
  flex-shrink: 0;
  border-radius: 8rpx;
}
.goods-cover-img {
}
.goods-con {
  display: flex;
  flex: 1;
  width: 0;
  margin-left: 22rpx;
  flex-direction: column;
  justify-content: space-between;
}
.goods-name-wrap {
}
.goods-name {
  font-size: 30rpx;
  line-height: 42rpx;
  margin-bottom: 10rpx;
}
.goods-price {
  font-size: 32rpx;
  color: #f65301;
}
.goods-price-unit {
  font-size: 24rpx;
}
.goods-price-num {
  font-size: 24rpx;
  color: #666;
}
.receiving-address {
  position: relative;
  z-index: 10;
}
.receiving-address__btn {
  position: absolute;
  z-index: 30;
  right: 10%;
  bottom: 25rpx;
  width: 80%;
  height: 48rpx;
  line-height: 48rpx;
  text-align: center;
  background: linear-gradient(135deg, #7ce166 0%, #4bb019 100%);
  border-radius: 27rpx;
  font-size: 24rpx;
  color: #fff;
}
.receiving-address__btn-hover {
  opacity: 0.5;
}
.f-cell-item {
  display: flex;
  justify-content: flex-end;
}
.f-cell-text {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 26rpx 32rpx;
}
.f-cell-item-input {
  width: 500rpx;
}
.footer-bar {
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 400;
  width: 750rpx;
  height: 98rpx;
  padding: 0 32rpx;
  background-color: #fff;
}
.footer-bar-place {
  height: 98rpx;
}
.footer-bar-total {
  font-size: 24rpx;
}
.footer-bar__total-price {
  font-size: 30rpx;
  color: #f65300;
}
.submit-button {
  height: 66rpx;
  line-height: 66rpx;
  padding: 0 40rpx;
  background: linear-gradient(323deg, #ff4564 0%, #f14141 14%, #fc843b 100%);
  border-radius: 200rpx 200rpx 200rpx 200rpx;
  border-radius: 32rpx;
  font-size: 30rpx;
  color: #fff;
}
.submit-button-hover {
  opacity: 0.5;
}
.specStyle {
  margin-top: 10rpx;
  padding: 5rpx 10rpx;
  background: rgba(239, 239, 244, 0.5);
  color: #999999;
  border-radius: 4rpx;
  font-size: 22rpx;
}
.err-tip {
  margin-bottom: 10rpx;
  text-align: center;
  color: #f65300;
}
.disable-btn {
  background: #b3b3b3 !important;
  color: #fff !important;
}
</style>
